package com.chenjj.seckill.servicelimit;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 限流 AOP
 */
@Aspect
public class ServiceLimitAspect {
	////每秒只发出1个令牌，此处是单进程服务的限流,内部采用令牌捅算法实现
	private static final  RateLimiter rateLimiter = RateLimiter.create(2.0);

	private Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.chenjj.seckill.servicelimit.ServiceLimitNonBlock)")
    public void ServiceLimitPonitCutNonBlock() {}

    @Pointcut("@annotation(com.chenjj.seckill.servicelimit.ServiceLimitBlock)")
    public void ServiceLimitPonitCutBlock() {}


    @Around("ServiceLimitPonitCutNonBlock()")
    public  Object aroundNonBlock(ProceedingJoinPoint joinPoint) {
        long timeout =1000;
        Boolean flag = rateLimiter.tryAcquire(); //非阻塞获取令牌
        Object obj = null;
        try {
            if(flag){
                obj = joinPoint.proceed();
            }else{
                logger.error("rateLimiter.tryAcquire failed!");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Around("ServiceLimitPonitCutBlock()")
    public  Object aroundBlock(ProceedingJoinPoint joinPoint) {
        double costTime = rateLimiter.acquire(); //阻塞获取令牌
        Object obj = null;
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
}
